package com.example.springboot.config.feign;

import com.alibaba.fastjson.JSON;
import com.example.springboot.entity.ResultData;
import com.example.springboot.exception.FeignException;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.nio.charset.Charset;

/**
 * @Author:ChenZhangKun
 * @Date: 2022/11/26 15:17
 */
@Slf4j
public class OpenFeignErrorDecoder implements ErrorDecoder {
    @Override
    public Exception decode(String s, Response response) {
        log.error("feign client error,response is {}:",response);
        try {
            //获取数据
            String errorContent = IOUtils.toString(response.body().asInputStream());
            String body = Util.toString(response.body().asReader(Charset.defaultCharset()));

            ResultData<?> resultData = JSON.parseObject(body,ResultData.class);
            if(!resultData.getCode().equals(200)){
                return new FeignException(resultData.getMessage());
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        return new FeignException("Feign client 调用异常");

    }
}
